#include "TcpClient.h"
#include "Socket.h"

XTcpClient::XTcpClient(/* args */)
{
}

XTcpClient::~XTcpClient()
{
}

bool XTcpClient::Connect(const std::string &strServer, const std::string &strPort)
{
#ifdef WINDOWS
	sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (sclient == INVALID_SOCKET)
	{
		printf("invalid socket !");
		return false;
	}

	sockaddr_in serAddr;
	serAddr.sin_family = AF_INET;
	serAddr.sin_port = htons(atoi(strPort.c_str()));
	serAddr.sin_addr.S_un.S_addr = inet_addr(strServer.c_str());
	if (connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)
	{
		printf("connect error !");
		closesocket(sclient);
		return false;
	}

#else

#endif
	return true;
}

bool XTcpClient::Send(const std::string strData) const
{
#ifdef WINDOWS
	int timeout = 15000;
	// char tStr[10];
	// itoa(timeout, tStr, 10);
	int ret = setsockopt(sclient, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout));
	if (ret < 0)
	{
		printf("send timeout\n");
	}

	send(sclient, strData.c_str(), strlen(strData.c_str()), 0);
#else
	struct timeval timeout = {3, 0}; //3s
	int ret = setsockopt(sclient, SOL_SOCKET, SO_SNDTIMEO, (const char *)&timeout, sizeof(timeout));
#endif
	return true;
}

char *XTcpClient::Receive(const int len) const
{
	char *recData = new char[len];
#ifdef WINDOWS
	int timeout = 30000; //3s
	// char tStr[10];
	// itoa(timeout, tStr, 10);
	int ret0 = setsockopt(sclient, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
	if (ret0 < 0)
	{
		printf("recv timeout\n");
	}
	int ret = recv(sclient, recData, len, 0);
	if (ret > 0)
	{
		recData[ret] = 0x00;
		// printf(recData);
	}else{
		printf("recv %d", ret);
	}
	closesocket(sclient);
	WSACleanup();
#else
	struct timeval timeout = {3, 0}; //3s
	int ret = setsockopt(sclient, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
#endif
	return recData;
}